import router from "@/router";
import { defineStore } from "pinia";
import { ref, watch } from "vue";
import type { RouteRecordNormalized } from "vue-router";
import useAppStore from "./useAppStore";
import useAuthStore from "./useAuthStore";

export default defineStore("tabStore", () => {
    /**
     * tab栏标签列表
     */
    const tabs = ref<RouteRecordNormalized[]>([])
    /**
     * 首页路由对象
     */
    const indexRoute = ref<RouteRecordNormalized>({} as any);
    /**
     * 当前激活的tabName
     */
    const activeTabName = ref("")
    /**
     * authStore
     */
    const authStore = useAuthStore()
    /**
     * appStore
     */
    const appStore = useAppStore()

    /**
     * 监听首页路由对象变化，如果首页路由对象变了，则初始化tabs，该监听只执行一次
     */
    watch(
        indexRoute,
        (index) => {
            if (index) tabs.value = [indexRoute.value];
        },
        { once: true }
    )

    /**
     * 当标签栏标签被点击
     * @param routePath 
     */
    const handleTabClick = (routePath: string) => {
        router.push(routePath)
            .then(() => (activeTabName.value = routePath))
    }

    /**
     * 增加一个tab
     * @param route 
     * @returns 
     */
    const addTab = (route: RouteRecordNormalized) => {
        if (authStore.authInfo?.token) {
            appStore.loadDict()
        }
        activeTabName.value = route.path
        // 如果当前列表里已存在，则直接返回
        if (tabs.value.some(tab => (tab.path === route.path))) {
            return
        }
        tabs.value.push(route)
    }

    /**
     * 关闭一个tab
     * @param routePath 
     */
    const closeTab = (routePath: string) => {
        const currentTab = tabs.value.filter(tab => (tab.path == routePath))[0]

        const index = tabs.value.indexOf(currentTab)
        // 如果当前移除的tab是当前激活的tab
        if (activeTabName.value === routePath) {
            if (index + 1 === tabs.value.length) {
                // 如果当前移除的tab是最后一个tab，则激活前面的tab
                activeTabName.value = tabs.value[index - 1].path
            } else {
                // 如果当前移除的tab不是最后一个tab，则激活后面那个tab
                activeTabName.value = tabs.value[index + 1].path
            }
        }
        // 删除指定的tab
        router.push(activeTabName.value)
            .then(() => tabs.value.splice(index, 1))
    }

    return {
        tabs,
        indexRoute,
        activeTabName,
        handleTabClick,
        addTab,
        closeTab
    }
})